package cn.edu.jxau.core.util;

import cn.edu.jxau.core.util.upload.FileUpload;
import cn.edu.jxau.core.vo.SpectrumFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * 序列化对象
 * <p>
 * MangoDai
 * 2017 08 28 11:26 AM
 */
public class SerializaObject {
    private static Logger logger = LoggerFactory.getLogger(SerializaObject.class);

    /**
     * 将对象序列化到相同路径中,存放的路径在对象的getFileDir，前提要实现序列化接口
     *
     * @param spectrumfile
     * @param filePath     保存的目录
     * @return
     */
    public static SpectrumFile writeObject(SpectrumFile spectrumfile, String filePath) {
        String fileName = StringUtil.getUUID() + FileUpload.SEPERATOR + spectrumfile.getSpectrumName();// 获取当前系统时间，确保文件不会重名
        File file = new File(filePath, fileName);
        spectrumfile.setFileName(fileName);
        spectrumfile.setFileDir(filePath);
        ObjectOutputStream outputStream = null;
        try {
            outputStream = new ObjectOutputStream(new FileOutputStream(file));
            outputStream.writeObject(spectrumfile);
            System.out.println("光谱文件序列化成功！");
            logger.debug("光谱文件序列化成功！"+ spectrumfile.getFileDir()+ " " +spectrumfile.getFileName());
            return spectrumfile;
        } catch (Exception e) {
            e.printStackTrace();
            logger.warn("文件序列化失败:{}", spectrumfile);
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 将对象序列化到相同路径中,存放的路径在对象的getFileDir
     *
     * @param spectrumfile 对象
     * @return 是否成功
     */
    public static SpectrumFile writeObject(SpectrumFile spectrumfile) {
         String filePath = spectrumfile.getFileDir();
        File file = new File(FileUpload.getBaseABSPath(), filePath);
        return writeObject(spectrumfile, file.getAbsolutePath());
    }


//    public static T write(T t, File path){
//        ObjectOutputStream outputStream = null;
//        try {
//            outputStream = new ObjectOutputStream(new FileOutputStream(path));
//            outputStream.writeObject(t);
//            System.out.println("光谱文件序列化成功！");
//            logger.debug("光谱文件序列化成功！", t);
//            return t;
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.warn("文件序列化失败:{}", t);
//        } finally {
//            try {
//                outputStream.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }
}
